<template>
    <div>
        <div>
            <van-nav-bar title="评论" left-text="返回" left-arrow @click-left="onClickLeft" />
        </div>
        <div>
            <van-card v-for="value in list" :key="value.item_id" :desc="value.content" :title="'评论人：'+value.username"
                thumb="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg">
                <template #tags>
                    <div class="van-card__desc van-ellipsis">{{ value.comment_time }}</div>
                </template>
                <template #footer>
                    <van-button type="success" size="small" @click="onShow(value.item_id)">修改</van-button>
                    <van-button type="danger" size="small" @click="onDelete(value.item_id)">删除</van-button>
                </template>
            </van-card>
        </div>
        <!-- 弹出层 -->
        <van-dialog v-model:show="show" title="修改评论" show-cancel-button @confirm="onSubmit" @cancel="onClose">
            <div>
                <van-cell-group inset>
                    <van-field v-model="message" rows="2" autosize label="修改评论" type="textarea" maxlength="60"
                        placeholder="请输入评论" show-word-limit />
                </van-cell-group>
            </div>
        </van-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getCommentApi, updateCommentApi, deleteCommentApi } from '@/api';
import { useCounterStore } from '@/stores/counter';
import { useRouter } from 'vue-router';
const store = useCounterStore();
const router = useRouter();
const list = ref([]);
const show = ref(false);
const message = ref('');
const itemId = ref(0);
const onDelete = e => {
    deleteComment(e);
};
const onShow = (e) => {
    itemId.value = e;
    show.value = true;
};
const onSubmit = () => {
    updateComment({
        itemId: itemId.value,
        content: message.value
    });
    message.value = '';
};
const onClose = () => {
    message.value = '';
};
const getComment = async e => {
    const res = await getCommentApi(e);
    list.value.push(...res);
};
const updateComment = async e => {
    const res = await updateCommentApi(e);
    if(res.success==="0"){}
    if(res.success==="1"){
        list.value.splice(0);
        getComment(store.userId);
    }
};
const deleteComment = async e => {
    const res = await deleteCommentApi(e);
    list.value.splice(list.value.findIndex(obj => obj.item_id === e), 1);
};
onMounted(() => {
    getComment(store.userId);
});
const onClickLeft = () => {
router.back()
};
</script>

<style scoped>
:deep(.van-field__word-limit){
    font-size: 12px;
    line-height: 20px;
}
</style>